﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunnyFunction
{
    public class GuessNum
    {
        private static List<int[]> NumList = new List<int[]>();

        private static int[] Result;
        private static int Num = 0;
        public static int Start()
        {
            Num = 0;
            Init();

            StartGuess(new int[] { 0, 3, 6, 7 });
            return Num;
        }

        private static void StartGuess(int[] vs)
        {
            Num++;

            if (Num > 8)
                Console.WriteLine("ERROR");
            CheckNum(vs,Result, out int A, out int B);
            Console.WriteLine("Guess: " + string.Join(" ", vs) + $" - {A}A{B}B");

            if (A == 4)
            {
                Console.WriteLine("Success => " + string.Join(" ", vs) + $"[{Num}]");
                return;
            }

            RemoveNum(vs, A, B);

            var next = GetNextNum();
            StartGuess(next);
        }

        private static int[] GetNextNum()
        {
            return NumList[0];
            //return NumList[new Random(Guid.NewGuid().GetHashCode()).Next(NumList.Count)];
        }

        private static void RemoveNum(int[] vs, int a, int b)
        {
            for (int i = NumList.Count - 1; i >= 0; i--)
            {
                CheckNum(vs, NumList[i], out int a1, out int b1);
                if (a1 != a || b1 != b)
                    NumList.RemoveAt(i);
            }
        }

        private static void CheckNum(int[] arr, int[] check, out int A, out int B)
        {
            A = 0;
            B = 0;
            for (int i = 0; i < 4; i++)
            {
                var num = arr[i];
                if (check[i] == num)
                    A++;
                else if (check.Contains(num))
                    B++;
            }
        }

        private static void Init()
        {
            NumList.Clear();
            for (int i = 0; i <= 9876; i++)
            {
                var arr = i.ToString("0000").ToCharArray().Select(t => int.Parse(t.ToString())).ToArray();
                var da = arr.Distinct().Count();
                if (da == 4)
                {
                    NumList.Add(arr);
                }
            }
            Random rand = new Random(Guid.NewGuid().GetHashCode());
            Result = NumList[rand.Next(NumList.Count)];

        }
    }
}
